from langchain_community.llms.tongyi import Tongyi
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables import RunnableWithMessageHistory

llm = Tongyi()

prompt = ChatPromptTemplate.from_messages([
    ('system', "你好，我是语言链，请问有什么可以帮助您？"),
    MessagesPlaceholder(variable_name="history"),
    ('human', '{input}')
])

chain = prompt | llm | StrOutputParser()

history = ChatMessageHistory()


def get_history():
    return history


runnable_history = RunnableWithMessageHistory(
    chain,
    get_history,
    input_messages_key="input",
    history_messages_key="history"
)


def get_history(user_input):
    ret = runnable_history.invoke({'input': user_input})
    print(ret)
    return ret
